﻿using System;
using System.Web.UI.WebControls;
using eCommerce.core;
using eCommerce.core.AdminGroup;
using eCommerce.core.AdminGroupUser;
using eCommerce.core.AdminUser;
using eCommerce.core.Authenticated;
using eCommerce.core.Helpers;

namespace eCommerce.cms.Controls.AdminUser
{
    public partial class AdminGroupUser : AuthenticatedControl
    {
        private int _adminUserId;
        protected void Page_Load(object sender, EventArgs e)
        {
            _adminUserId = Utils.GetIdFromRequestString(Utils.UserId, 0);

            ltMessage.Text = Utils.ShowMessage("Phân nhóm cho " + GetAdminUser(_adminUserId), MessageType.Information);

            if (!IsPostBack)            
                BindData();            
        }

        private void BindData()
        {
            lstGroup.DataSource = AdminGroupController.AdminGroup_GetAll();
            lstGroup.DataBind();

            // Thiếu kiểm tra xem thành viên này có được sử dụng chức năng này ko?            
            if (_adminUserId > 0)
            {
                var lstGroupId = (new AdminGroupUserController()).GetGroupsByUserId(_adminUserId);
                foreach (ListItem o in lstGroup.Items)
                {
                    foreach (var i in lstGroupId)
                    {
                        if (o.Value == i.AdminGroupId.ToString())
                        {
                            o.Selected = true;
                        }
                    }
                }
            }
        }        

        private string GetAdminUser(int adminUserId)
        {
            try
            {
                var adminUser = AdminUserController.AdminUser_GetById(adminUserId);
                return adminUser != null ? adminUser.FullName : string.Empty;
            }
            catch { return string.Empty; }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (_adminUserId > 0)
            {
                try
                {
                    var c = new AdminGroupUserController();
                    c.DeleteByUserId(_adminUserId);

                    foreach (ListItem item in lstGroup.Items)
                    {
                        var i = Utils.ToInt32(item.Value);
                        if (item.Selected && i != 0)
                            c.Create(i, _adminUserId);
                    }

                    ltMessage.Text = Utils.ShowMessage("Phân nhóm cho thành viên thành công!", MessageType.Success);
                }
                catch (Exception ex)
                {
                    ltMessage.Text = Utils.ShowMessage(ex.Message, MessageType.Failure);
                }   
            }            
        }
    }
}